package com.sl.au.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Chance;
import com.sl.au.entity.Quote;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteForeign;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.User;
import com.sl.au.service.QueryService;
import com.sl.au.service.QuoteForeignService;
import com.sl.au.service.QuoteSearchService;
import com.sl.au.service.QuoteService;
import com.sl.au.service.SectionService;

@Service("QuoteSearchService")
@Transactional
public class QuoteSearchServiceImpl extends BaseServiceImpl implements QuoteSearchService {

	@Autowired
	QueryService queryService;

	@Autowired
	QuoteForeignService quoteForeignService;

	@Autowired
	QuoteService quoteService;

	@Autowired
	SectionService sectionService;

	@Override
	public List<QuoteDevice> getQueryQuoteDevicesHql(int start, int length, Map<String, Object> condition, User user,
			String orderName, String dir) {
		Map<String, Object> namedParamsMap = new HashMap<String, Object>();
		StringBuilder hqlQuote = queryService.buildCombinedQueryHql("QuoteDevice", null, condition, namedParamsMap,null,
				user);
		StringBuilder hqlQuoteForeign = queryService.buildCombinedQueryHql("QuoteDevice", null, condition,
				namedParamsMap,null, user);
		String dataFilter = condition.get("dataFilter").toString();
		if (StringUtils.hasText(dataFilter)) {
			this.quoteDataFilter(hqlQuote, dataFilter, user, condition.get("userName"),
					condition.get("projectName"),condition.get("customerName"),condition.get("superiorArea"));
			this.quoteForeignDataFilter(hqlQuoteForeign, dataFilter, user, condition.get("userName"),
					condition.get("projectName"),condition.get("customerName"),condition.get("superiorArea"));
		} else
			return null;
		Map<String, Object> map2 = new HashMap<String, Object>();
		Map<String, Object> qMap2 = new HashMap<String, Object>();

		Map<String, Object> namedParamsMap2 = new HashMap<String, Object>();
		for (String key : namedParamsMap.keySet()) {
			qMap2.put("quoteDevice." + key, namedParamsMap.get(key));
		}
		map2.put("qMap", qMap2);
		List<QuoteDevice> list = new ArrayList<>();
		Query queryQuote = queryService.createQueryHql(hqlQuote.toString());
		Query queryQuoteForeign = queryService.createQueryHql(hqlQuoteForeign.toString());
		list = queryService.executeHql(queryQuote, namedParamsMap);
		List<QuoteDevice> list2 = queryService.executeHql(queryQuoteForeign, namedParamsMap);
		list.addAll(list2);
		// namedParamsMap2.putAll(namedParamsMap);
		return list.stream().distinct().sorted(Comparator.comparing(QuoteDevice::getCreateTime)).skip(start)
				.limit(length).collect(Collectors.toList());
	}

	@Override
	public long getQueryQuoteDevicesHqlCount(Map<String, Object> condition, User user) {
		Map<String, Object> namedParamsMap = new HashMap<String, Object>();
		StringBuilder hqlQuote = queryService.buildCombinedQueryHql("QuoteDevice", null, condition, namedParamsMap,null,
				user);
		StringBuilder hqlQuoteForeign = queryService.buildCombinedQueryHql("QuoteDevice", null, condition,
				namedParamsMap,null, user);
		String dataFilter = condition.get("dataFilter").toString();
		if (StringUtils.hasText(dataFilter)) {
			this.quoteDataFilter(hqlQuote, dataFilter, user, condition.get("userName"),
					condition.get("quoteSelect"),condition.get("customerName"),condition.get("superiorArea"));
			this.quoteForeignDataFilter(hqlQuoteForeign, dataFilter, user, condition.get("userName"),
					condition.get("quoteSelect"),condition.get("customerName"),condition.get("superiorArea"));
		}
		Map<String, Object> map2 = new HashMap<String, Object>();
		Map<String, Object> qMap2 = new HashMap<String, Object>();

		Map<String, Object> namedParamsMap2 = new HashMap<String, Object>();
		for (String key : namedParamsMap.keySet()) {
			qMap2.put("quoteDevice." + key, namedParamsMap.get(key));
		}
		map2.put("qMap", qMap2);
		List<QuoteDevice> list = new ArrayList<>();
		Query queryQuote = queryService.createQueryHql(hqlQuote.toString());
		Query queryQuoteForeign = queryService.createQueryHql(hqlQuoteForeign.toString());
		list = queryService.executeHql(queryQuote, namedParamsMap);
		List<QuoteDevice> list2 = queryService.executeHql(queryQuoteForeign, namedParamsMap);
		list.addAll(list2);
		// namedParamsMap2.putAll(namedParamsMap);
		return list.stream().distinct().collect(Collectors.toList()).size();
	}

	private void quoteDataFilter(StringBuilder hql, String dataFilter, User user, Object userName,
			Object projectName , Object customerName, Object superiorArea) {
		// 普通价格单数据范围过滤
		int mark = 2;
		if (dataFilter.equals("本部门") || dataFilter.equals("本科室")) {
			hql.append(" and (e.quote.user.saleArea.superior='" + user.getSaleArea().getSuperior() + "')")
		/*			.append(" and (e.quote.user.saleArea.id='" + user.getSaleArea().getId() + "')")*/
					.append("and (e.quote.auditState='" + "通过')")
			        .append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本片区")) {
			hql.append(" and (e.quote.user.saleArea.id='" + user.getSaleArea().getId() + "')")
					.append("and (e.quote.auditState='" + "通过')")
					.append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("所有")) {
			hql.append("and (e.quote.auditState='" + "通过')")
			.append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本人")) {
			hql.append(" and (e.quote.user.id='" + user.getId() + "') ")
			.append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		}
	}
	
	private void replaceDataFilter(StringBuilder hql, String dataFilter, User user, Object userName,
			Object projectName, Object customerName, Object superiorArea) {
		// 备件普通价格单数据范围过滤
		int mark = 2;
		if (dataFilter.equals("本部门") || dataFilter.equals("本科室")) {
			hql.append(" and (e.quote.user.saleArea.superior='" + user.getSaleArea().getSuperior() + "')")
		/*			.append(" and (e.quote.user.saleArea.id='" + user.getSaleArea().getId() + "')")*/
					.append("and (e.quote.auditState='" + "通过')");
			        
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本片区")) {
			hql.append(" and (e.quote.user.saleArea.id='" + user.getSaleArea().getId() + "')")
					.append("and (e.quote.auditState='" + "通过')");
					
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("所有")) {
			hql.append("and (e.quote.auditState='" + "通过')");
			
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本人")) {
			hql.append(" and (e.quote.user.id='" + user.getId() + "') ");
			
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		}
	}

	private void quoteForeignDataFilter(StringBuilder hql, String dataFilter, User user, Object userName,
			Object projectName, Object customerName, Object superiorArea) {
		// 外贸价格单 数据范围过滤
		int mark = 1;
		if (dataFilter.equals("本部门") || dataFilter.equals("本科室")) {
			hql.append(" and (e.quoteForeign.user.saleArea.superior='" + user.getSaleArea().getSuperior() + "')")
				/*	.append(" and (e.quoteForeign.user.saleArea.id='" + user.getSaleArea().getId() + "')")*/
					.append("and (e.quoteForeign.auditState='" + "通过')")
					.append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本片区")) {
			hql.append(" and (e.quoteForeign.user.saleArea.id='" + user.getSaleArea().getId() + "')")
					.append("and (e.quoteForeign.auditState='" + "通过')")
					.append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("所有")) {
			hql.append("and (e.quoteForeign.auditState='" + "通过')")
			.append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本人")) {
			hql.append(" and (e.quoteForeign.user.id='" + user.getId() + "') ")
			.append("and (e.inventoryState=0 or e.inventoryState is null)");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		}
	}

	private void repalceForeignDataFilter(StringBuilder hql, String dataFilter, User user, Object userName,
			Object projectName, Object customerName, Object superiorArea) {
		// 备件外贸价格单 数据范围过滤
		int mark = 1;
		if (dataFilter.equals("本部门") || dataFilter.equals("本科室")) {
			hql.append(" and (e.quoteForeign.user.saleArea.superior='" + user.getSaleArea().getSuperior() + "')")
				/*	.append(" and (e.quoteForeign.user.saleArea.id='" + user.getSaleArea().getId() + "')")*/
					.append("and (e.quoteForeign.auditState='" + "通过')");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本片区")) {
			hql.append(" and (e.quoteForeign.user.saleArea.id='" + user.getSaleArea().getId() + "')")
					.append("and (e.quoteForeign.auditState='" + "通过')");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("所有")) {
			hql.append("and (e.quoteForeign.auditState='" + "通过')");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		} else if (dataFilter.equals("本人")) {
			hql.append(" and (e.quoteForeign.user.id='" + user.getId() + "') ");
			bulidKeyWordInHql(hql, userName, projectName,customerName,superiorArea, mark);
		}
	}
	// 通过输入其他表中关键字过滤
	private void bulidKeyWordInHql(StringBuilder hql, Object userName, Object projectName, Object customerName, Object superiorArea,int mark) {
		if (mark == 1) {
			if (userName != null) {
				hql.append("and (e.quoteForeign.user.empLogin.userName like '%" + userName + "%')");
			}
			if (projectName != null) {
				hql.append("and (e.quoteForeign.name like'%" + projectName + "%')");
			}
			if (customerName != null) {
				hql.append("and (e.quoteForeign.customerName like'%" + customerName + "%')");
			}
			if(superiorArea!=null){
				hql.append("and (e.quoteForeign.user.saleArea.superiorArea like'%" + superiorArea + "%')");
			}
		} else {
			if (userName != null) {
				hql.append("and (e.quote.user.empLogin.userName like '%" + userName + "%')");
			}
			if (projectName != null) {
				hql.append("and (e.quote.name like '%" + projectName + "%')");
			}
			if (customerName != null) {
				hql.append("and (e.quote.customerName like '%" + customerName + "%')");
			}
			if(superiorArea!=null){
				hql.append("and (e.quote.user.saleArea.superiorArea like'%" + superiorArea + "%')");
			}
		}
	}

	@Override
	public List<QuoteReplacement> getQueryQuoteReplacementsHql(int start, int length, Map<String, Object> condition,
			User user, String orderName, String dir) {
		Map<String, Object> namedParamsMap = new HashMap<String, Object>();
		StringBuilder hqlQuote = queryService.buildCombinedQueryHql("QuoteReplacement", null, condition, namedParamsMap,null,
				user);
		StringBuilder hqlQuoteForeign = queryService.buildCombinedQueryHql("QuoteReplacement", null, condition,
				namedParamsMap,null, user);
		String dataFilter = condition.get("dataFilter").toString();
		if (StringUtils.hasText(dataFilter)) {
			this.replaceDataFilter(hqlQuote, dataFilter, user, condition.get("userName"),
					condition.get("projectName"),condition.get("customerName"),condition.get("superiorArea"));
			this.repalceForeignDataFilter(hqlQuoteForeign, dataFilter, user, condition.get("userName"),
					condition.get("projectName"),condition.get("customerName"),condition.get("superiorArea"));
		} else
			return null;
		Map<String, Object> map2 = new HashMap<String, Object>();
		Map<String, Object> qMap2 = new HashMap<String, Object>();

		Map<String, Object> namedParamsMap2 = new HashMap<String, Object>();
		for (String key : namedParamsMap.keySet()) {
			qMap2.put("quoteReplacement." + key, namedParamsMap.get(key));
		}
		map2.put("qMap", qMap2);
		List<QuoteReplacement> list = new ArrayList<>();
		Query queryQuote = queryService.createQueryHql(hqlQuote.toString());
		System.out.println(hqlQuote.toString());
		System.out.println(hqlQuoteForeign.toString());
		Query queryQuoteForeign = queryService.createQueryHql(hqlQuoteForeign.toString());
		list = queryService.executeHql(queryQuote, namedParamsMap);
		List<QuoteReplacement> list2 = queryService.executeHql(queryQuoteForeign, namedParamsMap);
		list.addAll(list2);
		// namedParamsMap2.putAll(namedParamsMap);
		return list.stream().distinct().sorted(Comparator.comparing(QuoteReplacement::getCreateTime)).skip(start)
				.limit(length).collect(Collectors.toList());
	}

	@Override
	public long getQueryQuoteReplacementsHqlCount(Map<String, Object> condition, User user) {
		// TODO Auto-generated method stub
		Map<String, Object> namedParamsMap = new HashMap<String, Object>();
		StringBuilder hqlQuote = queryService.buildCombinedQueryHql("QuoteReplacement", null, condition, namedParamsMap,null,
				user);
		StringBuilder hqlQuoteForeign = queryService.buildCombinedQueryHql("QuoteReplacement", null, condition,
				namedParamsMap,null, user);
		String dataFilter = condition.get("dataFilter").toString();
		if (StringUtils.hasText(dataFilter)) {
			this.replaceDataFilter(hqlQuote, dataFilter, user, condition.get("userName")
					, condition.get("projectName"), condition.get("customerName"), condition.get("superiorArea"));
			this.repalceForeignDataFilter(hqlQuoteForeign, dataFilter, user, condition.get("userName"),
					condition.get("projectName"), condition.get("customerName"),condition.get("superiorArea"));
		}
		Map<String, Object> map2 = new HashMap<String, Object>();
		Map<String, Object> qMap2 = new HashMap<String, Object>();
		Map<String, Object> namedParamsMap2 = new HashMap<String, Object>();
		for (String key : namedParamsMap.keySet()) {
			qMap2.put("quoteReplacement." + key, namedParamsMap.get(key));
		}
		map2.put("qMap", qMap2);
		List<QuoteReplacement> list = new ArrayList<>();
		Query queryQuote = queryService.createQueryHql(hqlQuote.toString());
		Query queryQuoteForeign = queryService.createQueryHql(hqlQuoteForeign.toString());
		list = queryService.executeHql(queryQuote, namedParamsMap);
		List<QuoteReplacement> list2 = queryService.executeHql(queryQuoteForeign, namedParamsMap);
		list.addAll(list2);
		// namedParamsMap2.putAll(namedParamsMap);
		return list.stream().distinct().collect(Collectors.toList()).size();
	}

}
